$(function () {
    let buttonGroup = [
        {
            id: 'btn_search',
            size: 'small',
            text: '查询',
            iconCls: 'icon-search',
            onClick: btn_search,
            plain: true
        },
        {
            id: 'btn_add',
            size: 'small',
            text: '外购入库',
            iconCls: 'icon-add',
            plain: true,
            // onClick: btn_add
            onClick:open_rcbp_win
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        // {
        //     id: 'btn_print',
        //     size: 'small',
        //     text: '打印',
        //     iconCls: 'icon-print',
        //     plain: true,
        //     onClick: btn_print
        // },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
    ];
    buttonGen($('#north'), buttonGroup);
    bindEnterEvents();

    setcombox(0)

});

//设置下拉
function setcombox(val) {
    if (val===0){
        let billtypedata=[{'sid':"织造发染厂"},{'sid':"销售出库"},{'sid':"外购入库"},{'sid':"染厂领料"},{'sid':"盘点单"}];
        $('#billtype').combobox({data:billtypedata, limitToList:true, required:true, readonly:true,valueField:'sid', textField:'sid'});
    }
    fetch('specification/listQuery').then(response => response.json()).then(data => {
        $('#ylgg').combobox({data:data, limitToList:true, required:true, valueField:'specName', textField:'specName'});
    });
    fetch('productInfo/listQuery').then(response => response.json()).then(data => {
        $('#pinming').combobox({data:data, limitToList:true, required:true, valueField:'productName', textField:'productName'});
    });
    fetch('meterLength/listQuery').then(response => response.json()).then(data => {
        $('#m_meter').combobox({data:data, limitToList:true, required:false, valueField:'meter_length', textField:'meter_length'});
    });

    $('#menfu').combobox({url: 'widthOfFabric/listQuery', method: 'GET', textField: 'wofName', valueField: 'wofName',});
    $('#kz').combobox({url: 'weightOfFabric/listQuery', method: 'GET', textField: 'wofName', valueField: 'wofName',});

    $.ajax({
        url: "contactCompany/listQuery",
        type: 'get',
        dataType: 'json',
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            // console.log(cdata);
            $('#clientname').combobox({
                data:cdata,
                limitToList:true,
                required:false,
                valueField:'id',
                textField:'companyName'
            });

        }
    });
}

function setBtnState(b) {
    if (b) {
        $('#btn_add').linkbutton('enable');
    } else {
        $('#btn_add').linkbutton('disable');
    }
}

//  选中事件
function onSelect(title, index) {
    function state(f) {
        if (f) {
            $('#start').datebox('disable');
            $('#end').datebox('disable');
        } else {
            $('#start').datebox('enable');
            $('#end').datebox('enable');
        }
    }

    switch (index) {
        case 0:
            if ($('#v_grid_1').data('kendoGrid') == undefined) {
                grid_2();
            }
            state(false);
            setBtnState(true);
            getgriddata(1);
            break;
        case 1:
            if ($('#v_grid_2').data('kendoGrid') == undefined) {
                grid_3();
            }
            state(true);
            setBtnState(false);
            getgriddata(2);
            break;
    }
}

/**
 * 2021年8月14日 16:27:40 chanchaw
 * 白坯管理 - 第二个标签页 - 白坯入库
 */
function grid_2() {
    let SUFFIX = "_b";
    let clientname = new kendo.data.DataSource({data: []});
    let bill_code = new kendo.data.DataSource({data: []});
    let contract = new kendo.data.DataSource({data: []});
    let order_code = new kendo.data.DataSource({data: []});
    let goods_name = new kendo.data.DataSource({data: []});
    let m_specification = new kendo.data.DataSource({data: []});
    let m_batch = new kendo.data.DataSource({data: []});
    let m_header = new kendo.data.DataSource({data: []});
    let m_height = new kendo.data.DataSource({data: []});
    let white_mf = new kendo.data.DataSource({data: []});
    let white_kz = new kendo.data.DataSource({data: []});
    let b_barcode = new kendo.data.DataSource({data: []});
    let billType = new kendo.data.DataSource({data: []});
    let white_mc = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                // id: 'id',
                fields: {
                    // createdate: {type: "date"},
                    ps: {type: "number"},
                    qty: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
        ],
        change: function (e) {
            // let data = this.data();
            var filtrer = this.filter();
            //获取所有数据
            var allData = this.data();
            //进行过滤条件的筛选
            var query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            var data = query.filter(filtrer).data;
            clientname.data(unique(data, 'clientname'));
            bill_code.data(unique(data, 'bill_code'));
            order_code.data(unique(data, 'order_code'));
            goods_name.data(unique(data, 'goods_name'));
            m_specification.data(unique(data, 'm_specification'));

            m_batch.data(unique(data, 'm_batch'));
            m_header.data(unique(data, 'm_header'));
            m_height.data(unique(data, 'm_height'));
            white_mf.data(unique(data, 'white_mf'));
            white_kz.data(unique(data, 'white_kz'));
            b_barcode.data(unique(data, 'b_barcode'));
            billType.data(unique(data, 'billType'));
            white_mc.data(unique(data, 'white_mc'));
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })

        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })

        }
    });
    let columns = [
        {
            field: "no",
            title: "#",
            filterable: false,
            template: "<span class='row_number'></span>",
            width: 40
        },
        {
            field: "id",
            title: '编号',
            width: 93,
            hidden: true,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
        },
        {
            field: "planid",
            title: '计划主键',
            width: 93,
            hidden: true,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "clientname",
            title: '客户',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: clientname}
        },
        {
            field: "bill_code",
            title: '发货单号',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: bill_code}
        },
        {
            field: "bill_date",
            title: '单据日期',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
            // filterable: {multi: true, search: true, dataSource: address}
        },
        {
            field: "order_code",
            title: '订单号',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: order_code}
        },
        {
            field: "goods_name",
            title: '品名',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: goods_name}
        },
        {
            field: "m_specification",
            title: '原料规格',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: m_specification}
        },
        {
            field: "m_batch",
            title: '原料批次',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "m_header",
            title: '头份',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: m_header}
        },
        {
            field: "ps",
            title: '匹数',
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty",
            title: '重量',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },

        {
            field: "m_height",
            title: '毛高',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: m_height}
        },
        {
            field: "white_mc",
            title: '米长',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: white_mc}
        },

        {
            field: "white_mf",
            title: '门幅',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: white_mf}
        },
        {
            field: "white_kz",
            title: '克重',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: white_kz}
        },
        {
            field: "b_barcode",
            title: '货架号',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: b_barcode}
        },
        // {
        //     field: "handlerName",
        //     title: '经手人',
        //     width: 93,
        //     attributes: {'class': 'kendo-custum-char'},
        //     headerAttributes: {'style': 'text-align:center;'},
        //     footerAttributes: {'style': 'color: red;text-align:center;'},
        //     // filterable: false
        //     filterable: {multi: true, search: true, dataSource: handlerName}
        // },
        {
            field: "billType",
            title: '单据类型',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: billType}
        },
        // {
        //     field: "b_data",
        //     title: '发货日期',
        //     width: 85,
        //     format: "{0: MM-dd}",
        //     headerAttributes: {'style': 'text-align:center;'},
        //     attributes: {'class': 'kendo-custum-char'},
        //     filterable: false
        // },
        // {
        //     field: "createTime",
        //     title: '制单时间',
        //     format: "{0: MM-dd HH:mm}",
        //     width: 85,
        //     headerAttributes: {'style': 'text-align:center;'},
        //     attributes: {'class': 'kendo-custum-char'},
        //     filterable: false
        // },
    ];
    let grid = $("#v_grid_1").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "白坯入库序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid_1').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
                let dataItem = kGrid.dataItem($(this));
                if (dataItem['is_audit'] != undefined && !dataItem['is_audit']) {
                    $(this).addClass('kendo-custum-non-checked');
                }
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_1').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });
    // 白坯管理 - 白坯入库 - 表格双击事件
    grid.on('dblclick', 'tr', function (e) {
        let dataItem = $('#v_grid_1').data('kendoGrid').dataItem(e.currentTarget);
        if (dataItem != undefined) {
            let id = dataItem.id;
            if (id == undefined) return;
            // $.get('productOutwardOrder/queryByPk/' + id, {}, function (data) {
            //     if (data != undefined) {
            //         btn_modify(data);
            //     }
            // }, 'json');
        }
    });
    grid.on('click', 'tr', function (e) {
        // let dataItem = $('#v_grid_1').data('kendoGrid').dataItem(e.currentTarget);
        // if (dataItem['is_audit']) {
        //     $('#btn_cancel_audit').linkbutton('enable')
        // } else {
        //     $('#btn_cancel_audit').linkbutton('disable')
        // }
    })
}

/**
 * 2021年8月18日 17:22:19chanchaw
 * 白坯管理 - 第三个标签页 - 白坯库存
 */
function grid_3() {
    let SUFFIX = "_c";
    let clientname = new kendo.data.DataSource({data: []});
    let bill_code = new kendo.data.DataSource({data: []});
    let contract = new kendo.data.DataSource({data: []});
    let order_code = new kendo.data.DataSource({data: []});
    let goods_name = new kendo.data.DataSource({data: []});

    let m_specification = new kendo.data.DataSource({data: []});
    let m_batch = new kendo.data.DataSource({data: []});
    let m_header = new kendo.data.DataSource({data: []});
    let m_height = new kendo.data.DataSource({data: []});
    let white_mf = new kendo.data.DataSource({data: []});
    let white_kz = new kendo.data.DataSource({data: []});
    let b_barcode = new kendo.data.DataSource({data: []});
    let billType = new kendo.data.DataSource({data: []});
    let white_mc = new kendo.data.DataSource({data: []});

    let dataSource = new kendo.data.DataSource({
        schema: {
            model: {
                // id: 'id',
                fields: {
                    // createdate: {type: "date"},
                    ps: {type: "number"},
                    qty: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "ps", aggregate: "sum"},
            {field: "qty", aggregate: "sum"},
        ],
        change: function (e) {
            // let data = this.data();
            //获取过滤条件
            var filtrer = this.filter();
            //获取所有数据
            var allData = this.data();
            //进行过滤条件的筛选
            var query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            var data = query.filter(filtrer).data;
            clientname.data(unique(data, 'clientname'));
            bill_code.data(unique(data, 'bill_code'));
            order_code.data(unique(data, 'order_code'));
            goods_name.data(unique(data, 'goods_name'));
            m_specification.data(unique(data, 'm_specification'));

            m_batch.data(unique(data, 'm_batch'));
            m_header.data(unique(data, 'm_header'));
            m_height.data(unique(data, 'm_height'));
            white_mf.data(unique(data, 'white_mf'));
            white_kz.data(unique(data, 'white_kz'));
            b_barcode.data(unique(data, 'b_barcode'));
            billType.data(unique(data, 'billType'));
            white_mc.data(unique(data, 'white_mc'));


        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })

        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })

        }
    });
    let columns = [
        {
            field: "no",
            title: "#",
            filterable: false,
            template: "<span class='row_number'></span>",
            width: 40
        },

        {
            field: "client",
            title: '客户编号',
            width: 93,
            hidden: true,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        },
        {
            field: "clientname",
            title: '客户',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: clientname}
        },
        {
            field: "goods_name",
            title: '品名',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: goods_name}
        },
        {
            field: "m_specification",
            title: '原料规格',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: m_specification}
        },
        // {
        //     field: "m_batch",
        //     title: '原料批次',
        //     width: 93,
        //     attributes: {'class': 'kendo-custum-char'},
        //     headerAttributes: {'style': 'text-align:center;'},
        //     footerAttributes: {'style': 'color: red;text-align:center;'},
        //     filterable: false
        // },
        // {
        //     field: "m_header",
        //     title: '头份',
        //     width: 93,
        //     attributes: {'class': 'kendo-custum-char'},
        //     headerAttributes: {'style': 'text-align:center;'},
        //     footerAttributes: {'style': 'color: red;text-align:center;'},
        //     // filterable: false
        //     filterable: {multi: true, search: true, dataSource: m_header}
        // },
        {
            field: "white_mc",
            title: '米长',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: white_mc}
        },

        {
            field: "ps",
            title: '匹数',
            width: 93,
            template: item => item['ps'] ? parseFloat(item['ps']).toFixed(0) : '',
            footerTemplate: '#=kendo.format("{0:n0}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },
        {
            field: "qty",
            title: '重量',
            width: 93,
            template: item => item['qty'] ? parseFloat(item['qty']).toFixed(1) : '',
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {'style': 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            headerAttributes: {'style': 'text-align:center;'},
            filterable: false
        },

        {
            field: "m_height",
            title: '毛高',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: m_height}
        },
        {
            field: "white_mf",
            title: '门幅',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: white_mf}
        },
        {
            field: "white_kz",
            title: '克重',
            width: 93,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            // filterable: false
            filterable: {multi: true, search: true, dataSource: white_kz}
        },

        {
            field: "memo",
            title: '.',
            width: 200,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {'style': 'text-align:center;'},
            footerAttributes: {'style': 'color: red;text-align:center;'},
            filterable: false
        }
    ];
    let grid = $("#v_grid_2").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "白坯库存.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
            });
        },
        columnHide: function (e) {
            // if (!$('#state').switchbutton('options').checked) return;
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
        },
        columnShow: function (e) {
            // if (!$('#state').switchbutton('options').checked) return;
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null, SUFFIX);
        },
        columnResize: function (e) {
            // if (!$('#state').switchbutton('options').checked) return;
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null, SUFFIX);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null, SUFFIX);
            }
        },
        columnReorder: function (e) {
            // if (!$('#state').switchbutton('options').checked) return;
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field'] + SUFFIX
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid_2').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });

    grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        let kGrid = $('#v_grid_2').data('kendoGrid');
        var selectedRows = kGrid.select();
        let div = $(`<div class="easyui-menu">
                         <div data-options="name:'生成发货',iconCls:'icon-ok'">盘点单</div>
                         <div data-options="name:'生成发货',iconCls:'icon-redo'">染厂领料</div>
                     </div>`);
        $('body').append(div);
        div.menu({
            onClick: function (item) {
                let name = item.text;
                if (selectedRows.length>1){$.messager.alert({title: '提示', msg: "不允许多选！！！"});return;}
                let strObj;
                for (let i = 0; i < selectedRows.length; i++) {
                    let dataItem = kGrid.dataItem(selectedRows[i]);
                    strObj={
                        "billtype": "盘点单",
                        "billdate": getCurrentDate(0),
                        "clientname": dataItem.client,
                        "ddh": "",
                        "pinming": dataItem.goods_name,
                        "ylgg": dataItem.m_specification,
                        "menfu": dataItem.white_mf,
                        "kz": dataItem.white_kz,
                        "m_height": dataItem.m_height,
                        "m_meter": dataItem.white_mc,
                        "ps": "",
                        "qty": "",
                        // "ps": -dataItem.ps,
                        // "qty": -dataItem.qty,
                        "memo": ""
                    }
                }
                switch (name) {
                    case '盘点单':

                        strObj.billtype='盘点单';
                        if(selectedRows.length>0){
                            $('#rcbp_win').dialog('open');
                            $('#rcbp_ff').form('load',strObj);
                        }else{
                            $.messager.alert({title: '提示', msg: "未选择数据！！！"});
                        }
                        break;
                    case '染厂领料':

                        strObj.billtype='染厂领料';
                        if(selectedRows.length>0){
                            $('#rcbp_win').dialog('open');
                            $('#rcbp_ff').form('load',strObj);
                        }else{
                            $.messager.alert({title: '提示', msg: "未选择数据！！！"});
                        }
                        break;
                }
            },
        });
        div.menu('show', {
            left: e.pageX,
            top: e.pageY
        })
    });
}

//清除过滤
function btn_cancel_filter() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_1').data('kendoGrid').dataSource.filter({});
            break;
        case 1:
            $('#v_grid_2').data('kendoGrid').dataSource.filter({});
            break;
    }
    $('#v_grid').data('kendoGrid').dataSource.filter({});
}

//  查询
function btn_search() {
    switch (getCurrentIndex()) {
        case 0:
            getgriddata(1);
            break;
        case 1:
            getgriddata(2);
            break;
        case 2:
            getgriddata(3);
            break;
    }
}

//报表数据源
function getgriddata(val) {
    var kGrid = getSelectedGrid();
    $.messager.progress({title: '', msg: '请稍等...', interval: 5000});
    $.ajax({
        url: "customize/callProc",
        type: 'post',
        data: JSON.stringify(['p_dye_grey_main',$('#start').datebox('getValue'),$('#end').datebox('getValue'),val]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            console.log(data);
            kGrid.dataSource.data(data);

        }, complete: function () {
            $.messager.progress('close');
        }

    })
}

function getCurrentIndex() {
    let tab = $('#tabs').tabs('getSelected');
    let index = $('#tabs').tabs('getTabIndex', tab);
    return index;
}

function btn_print() {
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            switch (getCurrentIndex()) {
                case 0:
                    reportlets.push({
                        reportlet: `${data.data}/发货序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 1:
                    reportlets.push({
                        reportlet: `${data.data}/白坯入库序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 2:
                    reportlets.push({
                        reportlet: `${data.data}/白坯库存序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 3:
                    if (!$('#contactCompanyId').combobox('getValue')) {
                        $.messager.alert('提示', '请选择客户再打印！', 'warning');
                        return;
                    }
                    reportlets.push({
                        reportlet: `${data.data}/应收款序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
                case 4:
                    if (!$('#contactCompanyId').combobox('getValue')) {
                        $.messager.alert('提示', '请选择客户再打印！', 'warning');
                        return;
                    }
                    reportlets.push({
                        reportlet: `${data.data}/已收款序时表打印.cpt`,
                        Sdate: $('#start').datebox('getValue'),
                        Edate: $('#end').datebox('getValue'),
                        clientName: $('#contactCompanyId').combobox('getValue') || '',
                        database: data.data
                    });
                    window.parent.FR.doURLPDFPrint({
                        url: $(window.parent.document.body).data('report_url'),
                        isPopUp: false,
                        data: {
                            reportlets: reportlets
                        }
                    })
                    break;
            }
        }
    }, 'json');
}

//列设置
function btn_open_column_list() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_1';
            break;
        case 1:
            kendoGridID = '#v_grid_2';
            break;
    }
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列',
                                         onClose:function(){$(this).dialog('destroy')}   " 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

//导出
function btn_export_excel() {
    switch (getCurrentIndex()) {
        case 0:
            $('#v_grid_1').data('kendoGrid').saveAsExcel();
            break;
        case 1:
            $('#v_grid_2').data('kendoGrid').saveAsExcel();
            break;
    }
}


//获取当前标签页的网格对象
function getSelectedGrid() {
    let kendoGridID = '';
    switch (getCurrentIndex()) {
        case 0:
            kendoGridID = '#v_grid_1';
            break;
        case 1:
            kendoGridID = '#v_grid_2';
            break;
    }
    return $(kendoGridID).data('kendoGrid');
}

function getCurrentSelectedGrid() {
    switch (getCurrentIndex()) {
        case 0:
            return $('#v_grid').data('kendoGrid')
        case 1:
            return $('#v_grid_1').data('kendoGrid');
    }
}

function btn_close() {
    window.parent.closeTab();
}
/***********************************************************************************************************
 *
 * */

//染厂白坯仓库  白坯入库
function close_rcbp() {
    $('#rcbp_win').dialog('close');
let obj={
    "billtype": "外购入库",
    "billdate": getCurrentDate(0),
    "clientname": "",
    "ddh": "",
    "pinming": "",
    "ylgg": "",
    "menfu": "",
    "kz": "",
    "m_height": "",
    "m_meter": "",
    "ps": "",
    "qty": "",
    "memo": ""
}
    $('#rcbp_ff').form('load',obj);

    // $('#client').combobox('setValue',"");
    // $('#manager').textbox('setValue',"");
    // $('#carnumber').textbox('setValue',"");
    // $('#memo').textbox('setValue',"");
    // $('#address').textbox('setValue',"");

}

function open_rcbp_win() {
    $('#rcbp_win').dialog('open');
    $('#billtype').combobox('setValue',"外购入库");

}

//生成发货
function save_rcbp() {
    // 使用 jQuery 简便的方式获取表单数据
    var formData = $('#rcbp_ff').serializeArray();
    var formDataObject = {};

    // 将数组转换为对象
    $.each(formData, function(index, field) {
        formDataObject[field.name] = field.value;
    });

    // 处理 formDataObject 对象，可以将其发送到服务器或执行其他操作
    console.log(formDataObject);

  let StrObj=  {
      "main": {
          "id": 0,
          "billDate": formDataObject.billdate + ' 00:00:00',
          "billType": formDataObject.billtype,
          "client": formDataObject.clientname,
          "remark": formDataObject.memo,
          "state": 1
      },
        "detailList": [
        {
            "id": 0,
            "orderCode": formDataObject.ddh,
            "goodsName": formDataObject.pinming,
            "mspecification": formDataObject.ylgg,
            "whiteMf": formDataObject.menfu,
            "whiteKz": formDataObject.kz,
            "mheight": formDataObject.m_height,
            "whiteMc": formDataObject.m_meter,
            "piece": formDataObject.ps,
            "kilo": formDataObject.qty,
            "remark": formDataObject.memo

            // "machine": "机台号",
            // "mbatch": "批次号",
            // "mheader": "头份",

        }
    ]
    }

    // $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', '确定生成 ' +formDataObject.billtype+' 单据？', function (r) {
        if (r) {
            $.ajax({
                url: 'dyeGrey/insertSelective',
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify(StrObj),
                // data:{"jrkId":50,"deviceId":223},
                contentType: "application/json;charset=UTF-8",
                success: function (cdata) {
                    console.log(cdata);
                    // console.log('完成发货！')
                    $.messager.show({title: '提示', msg: "生成 " +formDataObject.billtype+" 单完成！！！"});
                    close_rcbp();
                    btn_search();
                    // $('#tabs').tabs('select', 2);
                }
            })
        }
    })

}
